package com.flying.test.service;

import com.flying.test.model.GithubUser;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.web.client.RestTemplateBuilder;
import org.springframework.cloud.circuitbreaker.resilience4j.Resilience4JCircuitBreakerFactory;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;

@Service
@Slf4j
public class GithubService {
    @Value("${github.api.base-url}")
    private String githubBaseUrl;

    private RestTemplate restTemplate;

    private Resilience4JCircuitBreakerFactory resilience4JCircuitBreakerFactory;

    public GithubService(RestTemplateBuilder builder, Resilience4JCircuitBreakerFactory resilience4JCircuitBreakerFactory) {
        this.restTemplate = builder.build();
        this.resilience4JCircuitBreakerFactory = resilience4JCircuitBreakerFactory;
    }

    public GithubUser getGithubUserProfile(String username) {
        log.info("GithubBaseUrl:" + githubBaseUrl);
        return resilience4JCircuitBreakerFactory.create("Resilience4J")
                .run(() -> restTemplate.getForObject(githubBaseUrl + "/users/" + username, GithubUser.class),
                        t -> {
                            log.warn("fallback", t);
                            return getDefaultUser(username);
                        });
    }

    GithubUser getDefaultUser(String username) {
        log.info("---------getDefaultUser-----------");
        GithubUser user = new GithubUser();
        user.setId(-1L);
        user.setLogin("guest");
        user.setName("Guest");
        user.setPublicRepos(0);
        return user;
    }
}
